<template>
	<view class="admin-dashboard">
		<!-- 顶部导航和面包屑 -->
		<view class="header-section">
			<uni-stat-breadcrumb class="breadcrumb" />
			
			<!-- 欢迎横幅 -->
			<view class="welcome-banner">
				<view class="banner-content">
					<view class="welcome-text">
						<text class="welcome-title">欢迎回来，{{ currentUser.name || '管理员' }}！</text>
						<text class="welcome-subtitle">今天是{{ todayDate }}，祝您工作愉快</text>
					</view>
					<view class="banner-actions">
						<button class="logout-btn" @click="handleLogout" size="mini" type="default">
							<uni-icons type="person" size="16" color="#666"></uni-icons>
							<text>退出登录</text>
						</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 数据概览卡片 -->
		<view class="stats-section">
			<view class="stats-grid">
				<view class="stat-card">
					<view class="card-header">
						<text class="card-title">总反馈数</text>
						<uni-icons type="chatboxes" size="24" color="#409EFF"></uni-icons>
					</view>
					<view class="card-content">
						<text class="stat-number">{{ dashboardStats.totalFeedback }}</text>
						<text class="stat-change" :class="[getChangeClass(dashboardStats.feedbackChange)]">
							{{ formatChange(dashboardStats.feedbackChange) }}
						</text>
					</view>
				</view>

				<view class="stat-card">
					<view class="card-header">
						<text class="card-title">待处理</text>
						<uni-icons type="loop" size="24" color="#E6A23C"></uni-icons>
					</view>
					<view class="card-content">
						<text class="stat-number">{{ dashboardStats.pendingFeedback }}</text>
						<text class="stat-change" :class="[getChangeClass(dashboardStats.pendingChange)]">
							{{ formatChange(dashboardStats.pendingChange) }}
						</text>
					</view>
				</view>

				<view class="stat-card">
					<view class="card-header">
						<text class="card-title">已解决</text>
						<uni-icons type="checkmarkempty" size="24" color="#67C23A"></uni-icons>
					</view>
					<view class="card-content">
						<text class="stat-number">{{ dashboardStats.resolvedFeedback }}</text>
						<text class="stat-change" :class="[getChangeClass(dashboardStats.resolvedChange)]">
							{{ formatChange(dashboardStats.resolvedChange) }}
						</text>
					</view>
				</view>

				<view class="stat-card">
					<view class="card-header">
						<text class="card-title">用户数量</text>
						<uni-icons type="person" size="24" color="#909399"></uni-icons>
					</view>
					<view class="card-content">
						<text class="stat-number">{{ dashboardStats.totalUsers }}</text>
						<text class="stat-change" :class="[getChangeClass(dashboardStats.userChange)]">
							{{ formatChange(dashboardStats.userChange) }}
						</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 快捷操作 -->
		<view class="quick-actions-section">
			<uni-card title="快捷操作" :is-shadow="false">
				<view class="quick-actions-grid">
					<view class="action-item" @click="navigateToFeedback">
						<view class="action-icon">
							<uni-icons type="list" size="32" color="#409EFF"></uni-icons>
						</view>
						<text class="action-title">查看反馈</text>
						<text class="action-desc">管理用户反馈信息</text>
					</view>

					<view class="action-item" @click="navigateToUsers">
						<view class="action-icon">
							<uni-icons type="person" size="32" color="#67C23A"></uni-icons>
						</view>
						<text class="action-title">用户管理</text>
						<text class="action-desc">查看和管理用户</text>
					</view>

					<view class="action-item" @click="navigateToStats">
						<view class="action-icon">
							<uni-icons type="bars" size="32" color="#E6A23C"></uni-icons>
						</view>
						<text class="action-title">数据统计</text>
						<text class="action-desc">查看应用统计数据</text>
					</view>

					<view class="action-item" @click="navigateToSettings">
						<view class="action-icon">
							<uni-icons type="gear" size="32" color="#909399"></uni-icons>
						</view>
						<text class="action-title">系统设置</text>
						<text class="action-desc">配置系统参数</text>
					</view>
				</view>
			</uni-card>
		</view>

		<!-- 最近反馈 -->
		<view class="recent-feedback-section">
			<uni-card title="最近反馈" :is-shadow="false">
				<view class="feedback-list">
					<view v-for="(item, index) in recentFeedback" :key="index" class="feedback-item" @click="viewFeedbackDetail(item)">
						<view class="feedback-avatar">
							<uni-icons type="person" size="20" color="#909399"></uni-icons>
						</view>
						<view class="feedback-content">
							<view class="feedback-header">
								<text class="feedback-name">{{ item.name }}</text>
								<uni-tag :type="getStatusColor(item.status)" :text="getStatusText(item.status)" size="small"></uni-tag>
							</view>
							<text class="feedback-desc">{{ item.description.slice(0, 50) }}...</text>
							<text class="feedback-time">{{ formatTime(item.createTime) }}</text>
						</view>
						<view class="feedback-action">
							<uni-icons type="forward" size="16" color="#C0C4CC"></uni-icons>
						</view>
					</view>
					
					<view v-if="!recentFeedback.length" class="no-feedback">
						<uni-icons type="info" size="48" color="#C0C4CC"></uni-icons>
						<text>暂无反馈数据</text>
					</view>
				</view>
				
				<view class="view-all-btn" @click="navigateToFeedback">
					<text>查看全部反馈</text>
					<uni-icons type="forward" size="16" color="#409EFF"></uni-icons>
				</view>
			</uni-card>
		</view>

		<!-- 系统信息 -->
		<view class="system-info-section">
			<uni-card title="系统信息" :is-shadow="false">
				<view class="system-info">
					<view class="info-item">
						<text class="info-label">系统版本：</text>
						<text class="info-value">v1.0.0</text>
					</view>
					<view class="info-item">
						<text class="info-label">最后更新：</text>
						<text class="info-value">{{ lastUpdateTime }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">运行状态：</text>
						<text class="info-value status-good">正常运行</text>
					</view>
				</view>
			</uni-card>
		</view>
	</view>
</template>

<script>
import AuthManager from '@/utils/auth.js'

export default {
	data() {
		return {
			currentUser: {},
			dashboardStats: {
				totalFeedback: 0,
				pendingFeedback: 0,
				resolvedFeedback: 0,
				totalUsers: 0,
				feedbackChange: 0,
				pendingChange: 0,
				resolvedChange: 0,
				userChange: 0
			},
			recentFeedback: [],
			loading: false
		}
	},
	computed: {
		todayDate() {
			const today = new Date()
			return today.toLocaleDateString('zh-CN', {
				year: 'numeric',
				month: 'long',
				day: 'numeric',
				weekday: 'long'
			})
		},
		lastUpdateTime() {
			const now = new Date()
			return now.toLocaleString('zh-CN')
		}
	},
	async onLoad() {
		// 认证检查
		const isAuthed = await AuthManager.pageAuthGuard()
		if (!isAuthed) {
			return
		}
		
		// 获取用户信息
		this.currentUser = AuthManager.getUserInfo() || {}
		
		// 加载数据
		this.loadDashboardData()
	},
	methods: {
		// 处理登出
		handleLogout() {
			uni.showModal({
				title: '确认退出',
				content: '确定要退出登录吗？',
				success: (res) => {
					if (res.confirm) {
						AuthManager.logout()
						uni.showToast({
							title: '已退出登录',
							icon: 'success'
						})
						setTimeout(() => {
							AuthManager.redirectToLogin()
						}, 1500)
					}
				}
			})
		},

		// 加载仪表板数据
		async loadDashboardData() {
			this.loading = true
			try {
				await Promise.all([
					this.loadFeedbackStats(),
					this.loadRecentFeedback()
				])
			} catch (error) {
				console.error('加载仪表板数据失败:', error)
				uni.showToast({
					title: '加载数据失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},

		// 加载反馈统计数据
		async loadFeedbackStats() {
			try {
				const result = await uniCloud.callFunction({
					name: 'getFeedbackList',
					data: {
						pageSize: 1000, // 获取所有数据用于统计
						action: 'stats'
					}
				})

				if (result.result.success) {
					const feedbackList = result.result.data || []
					this.dashboardStats.totalFeedback = feedbackList.length
					this.dashboardStats.pendingFeedback = feedbackList.filter(item => item.status === 'pending').length
					this.dashboardStats.resolvedFeedback = feedbackList.filter(item => item.status === 'resolved').length
					
					// 模拟变化数据
					this.dashboardStats.feedbackChange = Math.floor(Math.random() * 20) - 10
					this.dashboardStats.pendingChange = Math.floor(Math.random() * 10) - 5
					this.dashboardStats.resolvedChange = Math.floor(Math.random() * 15) - 5
					this.dashboardStats.userChange = Math.floor(Math.random() * 10) - 5
					
					// 模拟用户数据
					const uniqueUsers = new Set(feedbackList.map(item => item.contact || item.name))
					this.dashboardStats.totalUsers = uniqueUsers.size
				}
			} catch (error) {
				console.error('获取反馈统计失败:', error)
			}
		},

		// 加载最近反馈
		async loadRecentFeedback() {
			try {
				const result = await uniCloud.callFunction({
					name: 'getFeedbackList',
					data: {
						pageSize: 5,
						action: 'list'
					}
				})

				if (result.result.success) {
					this.recentFeedback = result.result.data || []
				}
			} catch (error) {
				console.error('获取最近反馈失败:', error)
			}
		},

		// 格式化变化百分比
		formatChange(change) {
			if (change === 0) return '无变化'
			const prefix = change > 0 ? '+' : ''
			return `${prefix}${change}%`
		},

		// 获取变化样式类
		getChangeClass(change) {
			if (change > 0) return 'stat-increase'
			if (change < 0) return 'stat-decrease'
			return 'stat-neutral'
		},

		// 获取状态颜色
		getStatusColor(status) {
			switch (status) {
				case 'pending': return 'warning'
				case 'resolved': return 'success'
				case 'processing': return 'primary'
				default: return 'default'
			}
		},

		// 获取状态文本
		getStatusText(status) {
			switch (status) {
				case 'pending': return '待处理'
				case 'resolved': return '已解决'
				case 'processing': return '处理中'
				default: return '未知'
			}
		},

		// 格式化时间
		formatTime(timestamp) {
			if (!timestamp) return ''
			const date = new Date(timestamp)
			const now = new Date()
			const diff = now - date
			
			if (diff < 60000) { // 1分钟内
				return '刚刚'
			} else if (diff < 3600000) { // 1小时内
				return Math.floor(diff / 60000) + '分钟前'
			} else if (diff < 86400000) { // 1天内
				return Math.floor(diff / 3600000) + '小时前'
			} else {
				return date.toLocaleDateString('zh-CN')
			}
		},

		// 导航方法
		navigateToFeedback() {
			uni.navigateTo({
				url: '/pages/feedback/feedback-list'
			})
		},

		navigateToUsers() {
			uni.showToast({
				title: '功能开发中',
				icon: 'none'
			})
		},

		navigateToStats() {
			uni.showToast({
				title: '功能开发中',
				icon: 'none'
			})
		},

		navigateToSettings() {
			uni.showToast({
				title: '功能开发中',
				icon: 'none'
			})
		},

		// 查看反馈详情
		viewFeedbackDetail(feedback) {
			uni.navigateTo({
				url: `/pages/feedback/feedback-detail?id=${feedback._id}`
			})
		}
	}
}
</script>

<style scoped>
.admin-dashboard {
	padding: 20px;
	background-color: #f5f5f5;
	min-height: 100vh;
}

/* 头部部分 */
.header-section {
	margin-bottom: 30px;
}

.breadcrumb {
	margin-bottom: 20px;
}

.welcome-banner {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 12px;
	padding: 24px;
	color: white;
	box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
}

.banner-content {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.welcome-text {
	flex: 1;
}

.banner-actions {
	margin-left: 20px;
}

.logout-btn {
	background: rgba(255, 255, 255, 0.2);
	color: white;
	border: 1px solid rgba(255, 255, 255, 0.3);
	border-radius: 6px;
	padding: 8px 16px;
	font-size: 12px;
	display: flex;
	align-items: center;
	gap: 4px;
	transition: all 0.2s;
}

.logout-btn:hover {
	background: rgba(255, 255, 255, 0.3);
	border-color: rgba(255, 255, 255, 0.5);
}

.welcome-title {
	font-size: 24px;
	font-weight: bold;
	display: block;
	margin-bottom: 8px;
}

.welcome-subtitle {
	font-size: 14px;
	opacity: 0.9;
}

.banner-icon {
	margin-left: 20px;
}

/* 统计卡片 */
.stats-section {
	margin-bottom: 30px;
}

.stats-grid {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
	gap: 20px;
	margin-bottom: 20px;
}

.stat-card {
	background: white;
	padding: 24px;
	border-radius: 12px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
	transition: transform 0.2s, box-shadow 0.2s;
}

.stat-card:hover {
	transform: translateY(-2px);
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
}

.card-title {
	font-size: 14px;
	color: #666;
	font-weight: 500;
}

.card-content {
	display: flex;
	flex-direction: column;
	gap: 8px;
}

.stat-number {
	font-size: 32px;
	font-weight: bold;
	color: #333;
}

.stat-change {
	font-size: 12px;
	font-weight: 500;
}

.stat-increase {
	color: #67C23A;
}

.stat-decrease {
	color: #F56C6C;
}

.stat-neutral {
	color: #909399;
}

/* 快捷操作 */
.quick-actions-section {
	margin-bottom: 30px;
}

.quick-actions-grid {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
	gap: 16px;
	padding: 20px 0;
}

.action-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	text-align: center;
	padding: 20px;
	border-radius: 8px;
	background: #f8f9fa;
	transition: all 0.2s;
	cursor: pointer;
}

.action-item:hover {
	background: #e9ecef;
	transform: translateY(-2px);
}

.action-icon {
	margin-bottom: 12px;
}

.action-title {
	font-size: 16px;
	font-weight: 600;
	color: #333;
	margin-bottom: 4px;
}

.action-desc {
	font-size: 12px;
	color: #666;
}

/* 最近反馈 */
.recent-feedback-section {
	margin-bottom: 30px;
}

.feedback-list {
	padding: 20px 0;
}

.feedback-item {
	display: flex;
	align-items: center;
	padding: 16px 0;
	border-bottom: 1px solid #f0f0f0;
	cursor: pointer;
	transition: background-color 0.2s;
}

.feedback-item:hover {
	background-color: #f8f9fa;
}

.feedback-item:last-child {
	border-bottom: none;
}

.feedback-avatar {
	width: 40px;
	height: 40px;
	border-radius: 50%;
	background: #f0f0f0;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 16px;
	flex-shrink: 0;
}

.feedback-content {
	flex: 1;
	min-width: 0;
}

.feedback-header {
	display: flex;
	align-items: center;
	gap: 8px;
	margin-bottom: 4px;
}

.feedback-name {
	font-size: 14px;
	font-weight: 600;
	color: #333;
}

.feedback-desc {
	font-size: 13px;
	color: #666;
	margin-bottom: 4px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.feedback-time {
	font-size: 12px;
	color: #999;
}

.feedback-action {
	margin-left: 16px;
	flex-shrink: 0;
}

.no-feedback {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 40px 20px;
	color: #999;
	text-align: center;
}

.no-feedback text {
	margin-top: 12px;
	font-size: 14px;
}

.view-all-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 8px;
	padding: 12px;
	margin-top: 16px;
	border-top: 1px solid #f0f0f0;
	color: #409EFF;
	font-size: 14px;
	cursor: pointer;
	transition: color 0.2s;
}

.view-all-btn:hover {
	color: #66b1ff;
}

/* 系统信息 */
.system-info-section {
	margin-bottom: 30px;
}

.system-info {
	padding: 20px 0;
}

.info-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 12px 0;
	border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
	border-bottom: none;
}

.info-label {
	font-size: 14px;
	color: #666;
}

.info-value {
	font-size: 14px;
	color: #333;
	font-weight: 500;
}

.status-good {
	color: #67C23A !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
	.admin-dashboard {
		padding: 16px;
	}
	
	.stats-grid {
		grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
		gap: 16px;
	}
	
	.welcome-banner {
		padding: 20px;
	}
	
	.banner-content {
		flex-direction: column;
		text-align: center;
		gap: 16px;
	}
	
	.welcome-title {
		font-size: 20px;
	}
	
	.stat-number {
		font-size: 28px;
	}
	
	.quick-actions-grid {
		grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
		gap: 12px;
	}
	
	.action-item {
		padding: 16px 12px;
	}
}
</style>
